﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using MINERP.DAL;
using MINERP.DAL.QC;
using MINERP.COM;
using MINERP.BLL.Common;
using MINERP.MODEL.FoundationModel;

namespace MINERP.BLL.QC
{
    public class QCBLL
    {
        QCDAL _dal = new QCDAL();
        private List<Shop> GetShopList()
        {
            using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
                return entities.Shop.Where(s => s.Status == 1).ToList();
            }
        }
        /// <summary>
        /// 检查产品是否存在
        /// </summary>
        /// <param name="productCode"></param>
        /// <returns></returns>
        public bool IsProductExist(string productCode)
        {
            bool flag = true;
            using (newSampleYPDBEntities Entities = new newSampleYPDBEntities())
            {
                orderInfo oi = Entities.orderInfo.FirstOrDefault(o => o.OrderProductCode == productCode);
                if (oi == null)
                {
                    flag = false;
                }
            }

            return flag;
        }
        public List<string> GetShops()
        {
            List<string> list = new List<string>();
            list.Add("          ");
            foreach (var item in GetShopList())
            {
                list.Add(item.shopName);
            }
            list.Sort();
            return list;
        }


        public DataTable GetProductList(string shopName, string customerName, string productName, DateTime startTime, DateTime endTime)
        {
            DataTable dt = null;
            dt = QCDAL.GetProductList(shopName, customerName, productName, startTime, endTime);
            return dt;

        }

        public DataTable GetPhotoInfosByPhotoCode(string photoBarcode)
        {
            DataTable dt = null;
            dt = QCDAL.GetPhotoInfosByPhotoCode(photoBarcode);
            
            return dt;

        }
        /// <summary>
        /// 取得打印报表数据
        /// </summary>
        /// <param name="inGridId"></param>
        /// <param name="inProduct"></param>
        public DataSet GetReportdata(string inProduct, string inGridName)
        {
            DataSet ds = new DataSet();
            orderInfo product = null;
            using (newSampleYPDBEntities Entities = new newSampleYPDBEntities())
            {
                product = Entities.orderInfo.FirstOrDefault(o => o.OrderProductCode == inProduct);

                if (product == null)
                {
                    return ds;
                }
                if (!product.Tb_OrderBagReference.IsLoaded)
                {
                    product.Tb_OrderBagReference.Load();
                }
                if (!product.Tb_OrderBag.ShopReference.IsLoaded)
                {
                    product.Tb_OrderBag.ShopReference.Load();
                }


                DataTable infoTable = CreateInfoTable();
                infoTable.TableName = "infoTable";
                DataRow rowInfo = infoTable.NewRow();
                rowInfo["BagCode"] = product.Tb_OrderBag.BagCode;
                rowInfo["BagName"] = product.Tb_OrderBag.BagName;
                rowInfo["shopName"] = product.Tb_OrderBag.Shop.shopName;
                rowInfo["OrderProductCode"] = "*" + product.OrderProductCode + "*";
                rowInfo["OrderProductName"] = product.OrderProductName;
                rowInfo["CtmName"] = product.CtmName;
                rowInfo["productNum"] = product.productNum;
                rowInfo["remark"] = product.Remark;
                rowInfo["GridName"] = inGridName;
                rowInfo["OrderTime"] = product.Tb_OrderBag.OrderTime;

                infoTable.Rows.Add(rowInfo);
                if (product.Priority >= 11)
                {
                    rowInfo["Priority"] = "特急件";
                }
                else if (product.Priority < 11 && product.Priority >= 6)
                {
                    rowInfo["Priority"] = "急件";
                }
                else
                {
                    rowInfo["Priority"] = "";
                }

                DataTable photoTable = CreatePhotoInfoTable();
                Dictionary<string, int> photos = new Dictionary<string, int>();
                //Dictionary<string, int> photosCM = new Dictionary<string, int>();
                if (!product.photoInfo.IsLoaded)
                {
                    product.photoInfo.Load();
                }
                foreach (photoInfo list in product.photoInfo)
                {
                    string photoSize = "" + Math.Round(list.Width, 2) + "×" + Math.Round(list.Height, 2) + "in(" + Math.Round(list.Width * 2.54, 2) + "×" + Math.Round(list.Height * 2.54, 2) + "cm)";
                    string photoSize1 = "" + Math.Round(list.Height, 2) + "×" + Math.Round(list.Width, 2) + "in(" + Math.Round(list.Height * 2.54, 2) + "×" + Math.Round(list.Width * 2.54, 2) + "cm)";

                    //string photoSizeCM = Math.Round(list.Width * 2.54, 2) + "×" + Math.Round(list.Height, 2);
                    if (photos.Keys.Contains(photoSize))
                    {
                        photos[photoSize] += 1;
                    }
                    else if (photos.Keys.Contains(photoSize1))
                    {
                        photos[photoSize1] += 1;
                    }
                    else
                    {
                        photos.Add(photoSize, 1);
                        //photosCM.Add(photoSizeCM, 1);
                    }
                }
                foreach (var list in photos)
                {
                    DataRow row = photoTable.NewRow();
                    row["Size"] = list.Key;
                    row["Num"] = list.Value;
                    photoTable.Rows.Add(row);

                }
                photoTable.TableName = "photoTable";

                if (!product.WorkOrderFlowList.IsLoaded)
                {
                    product.WorkOrderFlowList.Load();
                }
                //List<WorkOrderFlowList> flows = _dal.GetAllFlowByProductId(inProduct).OrderBy(p => p.WorkOrder).ToList();
                string strFlow = string.Empty;
                foreach (WorkOrderFlowList list in product.WorkOrderFlowList.OrderBy(p => p.WorkOrder))
                {
                    if (!list.tb_TechReference.IsLoaded)
                    {
                        list.tb_TechReference.Load();
                    }
                    strFlow = strFlow + list.tb_Tech.TechName + "->";
                }
                strFlow = strFlow.Trim("->".ToCharArray());
                DataTable flowTable = CreateTechFlow();
                //foreach (WorkOrderFlowList list in flows)
                //{
                //    if (!list.tb_TechReference.IsLoaded)
                //    {
                //        list.tb_TechReference.Load();
                //    }
                //    users user = _dal.GetUserById(list.UserId);
                //    DataRow row = flowTable.NewRow();
                //    row["TechName"] = list.tb_Tech.TechName;
                //    if (user != null)
                //    {
                //        row["UserName"] = user.UserName;
                //    }
                //    else
                //    {
                //        row["UserName"] = "";
                //    }
                //    flowTable.Rows.Add(row);
                //}
                DataRow rowt = flowTable.NewRow();
                rowt["TechName"] = strFlow;
                rowt["UserName"] = "0";
                flowTable.Rows.Add(rowt);
                flowTable.TableName = "flowTable";

                ds.Tables.Add(photoTable);
                ds.Tables.Add(infoTable);
                ds.Tables.Add(flowTable);
            }
            return ds;
        }

        /// <summary>
        ///  基本信息表
        /// </summary>
        /// <returns></returns>
        public DataTable CreateInfoTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BagCode", typeof(string));
            table.Columns.Add("BagName", typeof(string));
            table.Columns.Add("shopName", typeof(string));
            table.Columns.Add("OrderProductCode", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("productNum", typeof(int));
            table.Columns.Add("remark", typeof(string));
            table.Columns.Add("GridName", typeof(string));
            table.Columns.Add("Priority", typeof(string));
            table.Columns.Add("OrderTime", typeof(string));
            return table;

        }

        /// <summary>
        /// 照片信息
        /// </summary>
        /// <returns></returns>
        public DataTable CreatePhotoInfoTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Size", typeof(string));
            //table.Columns.Add("Size1", typeof(string));
            table.Columns.Add("Num", typeof(int));
            return table;
        }

        /// <summary>
        /// 流程信息
        /// </summary>
        /// <returns></returns>
        public DataTable CreateTechFlow()
        {
            DataTable table = new DataTable();
            table.Columns.Add("TechName", typeof(string));
            table.Columns.Add("UserName", typeof(string));
            return table;
        }
        public DataTable GetPrintInfo(string inProductId)
        {
            return _dal.GetPrintInfo(inProductId);
        }

        public List<CheckPhoto> GetPhotosByOrderProductCode(string orderProductCode)
        {
            try
            {
                List<CheckPhoto> photos = new List<CheckPhoto>();
                DataTable dt = _dal.GetPhotoByOrderProductCode(orderProductCode);
                foreach (DataRow r in dt.Rows)
                {
                    CheckPhoto photo = new CheckPhoto();
                    photo.OrderProductCode = r["OrderProductCode"].ToString();
                    photo.OrderProductName = r["OrderProductName"].ToString();
                    photo.PhotoBarCode = r["PhotoBarCode"].ToString();
                    photo.PicPath = r["PicPath"].ToString();
                    photo.PhotoRemark = r["PhotoRemark"].ToString();
                    photo.CtmName = r["CtmName"].ToString();
                    photo.ShopName = r["ShopName"].ToString();
                    photo.PhotoNum = Convert.ToInt32(r["TotalNum"]);
                    photo.ProductNum = Convert.ToInt32(r["productNum"]);

                    photos.Add(photo);
                }
                return photos.OrderBy(p => p.PhotoName).ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public class CheckPhoto
        {
            public string PhotoBarCode { get; set; }
            public string PicPath { get; set; }
            public string PhotoRemark { get; set; }
            public string OrderProductCode { get; set; }
            public string OrderProductName { get; set; }
            public string CtmName { get; set; }
            public string ShopName { get; set; }
            public string PhotoName
            {
                get
                {
                    if (PicPath != null)
                    {
                        return PicPath.Substring(PicPath.LastIndexOf('\\') + 1);
                    }
                    else
                    {
                        return "";
                    }
                }
            }
            public int PhotoNum { get; set; }
            public int ProductNum { get; set; }
        }

        //完成工厂端生产
        public void CompletedFactoryWork(string orderProductCode)
        {
            int orderproductid = GetOrderInfo(orderProductCode);
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                OutProcessRecord opr = dataBase.OutProcessRecord.FirstOrDefault(op => op.orderInfo.OrderProductId == orderproductid);
                if (opr != null)
                {
                    opr.EndProductTime = DateTime.Now;
                    opr.Status2 = (int)OutProcessRecordStatus2.Complete;
                    dataBase.SaveChanges();
                }
            }
        }

        public bool UpdateWorkFlowList(string productCode, int userid, int techid)
        {
            WorkFlowListBLL workFlowListbll = new WorkFlowListBLL();
            int orderproductid = GetOrderInfo(productCode);
            if (orderproductid != 0)
            {
                return workFlowListbll.OverCurTech(techid, userid, orderproductid);
            }
            else
            {
                return false;
            }
        }
        public int GetOrderInfo(string productCode)
        {
            int orderProductid = 0;
            using (newSampleYPDBEntities Entities = new newSampleYPDBEntities())
            {
                orderInfo oi = Entities.orderInfo.FirstOrDefault(o => o.OrderProductCode == productCode && o.ProductType == (int)OrderInfoType.Normal);
                if (oi != null)
                {
                    orderProductid = oi.OrderProductId;
                }
            }
            return orderProductid;
        }

        public bool IsNeedSetCompleted(string productCode, int techid)
        {
            bool flag = false;

            using (newSampleYPDBEntities Entities = new newSampleYPDBEntities())
            {


                orderInfo oi = Entities.orderInfo.FirstOrDefault(o => o.OrderProductCode == productCode && (o.OrderType == (int)OrderInfoType.Normal || o.OrderType == (int)OrderInfoType.OutReturnInfo));
                if (oi == null)
                {
                    return false;
                }
                ///修改委外记录
                OutProcessRecord outProcessRecord = Entities.OutProcessRecord.FirstOrDefault(p => p.orderInfo.OrderProductCode == productCode);
                if (outProcessRecord != null)
                {
                    outProcessRecord.EndProductTime = DateTime.Now;
                    outProcessRecord.Status2 = (int)OutProcessRecordStatus2.Complete;
                    outProcessRecord.OperateUser = 0;
                }
                if (!oi.WorkOrderFlowList.IsLoaded)
                {
                    oi.WorkOrderFlowList.Load();
                }
                foreach (var item in oi.WorkOrderFlowList)
                {
                    if (!item.tb_TechReference.IsLoaded)
                    {
                        item.tb_TechReference.Load();
                    }
                }
                WorkOrderFlowList list = oi.WorkOrderFlowList.FirstOrDefault(w => w.tb_Tech.TechId == techid);
                if (list != null)
                {
                    if (list.Status == (int)OrderFlowListStatus.Useable)
                    {
                        flag = true;
                    }
                }
                Entities.SaveChanges();
            }
            return flag;

        }
    }
}
